﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using HslCommunication.Core.Net;
using HslCommunication.LogNet;

namespace HslCommunication.Profinet.Melsec
{
	/// <inheritdoc />
	// Token: 0x02000075 RID: 117
	public class MelsecMcUdpServer : MelsecMcServer
	{
		/// <summary>
		/// 实例化一个默认参数的mc协议的服务器<br />
		/// Instantiate a mc protocol server with default parameters
		/// </summary>
		/// <param name="isBinary">是否是二进制，默认是二进制，否则是ASCII格式</param>
		// Token: 0x060009A6 RID: 2470 RVA: 0x0003940B File Offset: 0x0003760B
		public MelsecMcUdpServer(bool isBinary = true) : base(isBinary)
		{
		}

		/// <summary>
		/// 获取或设置一次接收时的数据长度，默认2KB数据长度
		/// </summary>
		// Token: 0x1700019A RID: 410
		// (get) Token: 0x060009A7 RID: 2471 RVA: 0x00039421 File Offset: 0x00037621
		// (set) Token: 0x060009A8 RID: 2472 RVA: 0x00039429 File Offset: 0x00037629
		public int ReceiveCacheLength { get; set; } = 2048;

		/// <inheritdoc />
		// Token: 0x060009A9 RID: 2473 RVA: 0x00039434 File Offset: 0x00037634
		public override void ServerStart(int port)
		{
			bool flag = !base.IsStarted;
			if (flag)
			{
				this.StartInitialization();
				this.CoreSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
				this.CoreSocket.Bind(new IPEndPoint(IPAddress.Any, port));
				this.RefreshReceive();
				base.IsStarted = true;
				base.Port = port;
				ILogNet logNet = base.LogNet;
				if (logNet != null)
				{
					logNet.WriteInfo(this.ToString(), StringResources.Language.NetEngineStart);
				}
			}
		}

		/// <summary>
		/// 重新开始接收数据
		/// </summary>
		/// <exception cref="T:System.ArgumentNullException"></exception>
		// Token: 0x060009AA RID: 2474 RVA: 0x000394B8 File Offset: 0x000376B8
		private void RefreshReceive()
		{
			AppSession appSession = new AppSession();
			appSession.WorkSocket = this.CoreSocket;
			appSession.UdpEndPoint = new IPEndPoint(IPAddress.Any, 0);
			appSession.BytesContent = new byte[this.ReceiveCacheLength];
			this.CoreSocket.BeginReceiveFrom(appSession.BytesContent, 0, this.ReceiveCacheLength, SocketFlags.None, ref appSession.UdpEndPoint, new AsyncCallback(this.AsyncCallback), appSession);
		}

		// Token: 0x060009AB RID: 2475 RVA: 0x0003952C File Offset: 0x0003772C
		private void AsyncCallback(IAsyncResult ar)
		{
			AppSession appSession = ar.AsyncState as AppSession;
			bool flag = appSession != null;
			if (flag)
			{
				try
				{
					int num = appSession.WorkSocket.EndReceiveFrom(ar, ref appSession.UdpEndPoint);
					bool flag2 = !Authorization.asdniasnfaksndiqwhawfskhfaiw();
					if (flag2)
					{
						base.RemoveClient(appSession, "");
					}
					else
					{
						this.RefreshReceive();
						byte[] array = new byte[num];
						Array.Copy(appSession.BytesContent, 0, array, 0, num);
						bool isBinary = base.IsBinary;
						byte[] array2;
						if (isBinary)
						{
							array2 = this.ReadFromMcCore(array.RemoveBegin(11));
						}
						else
						{
							array2 = this.ReadFromMcAsciiCore(array.RemoveBegin(22));
						}
						ILogNet logNet = base.LogNet;
						if (logNet != null)
						{
							logNet.WriteDebug(this.ToString(), "Udp " + StringResources.Language.Receive + "：" + (base.IsBinary ? array.ToHexString(' ') : Encoding.ASCII.GetString(array)));
						}
						bool flag3 = array2 != null;
						if (flag3)
						{
							appSession.WorkSocket.SendTo(array2, array2.Length, SocketFlags.None, appSession.UdpEndPoint);
							ILogNet logNet2 = base.LogNet;
							if (logNet2 != null)
							{
								logNet2.WriteDebug(this.ToString(), "Udp " + StringResources.Language.Send + "：" + (base.IsBinary ? array2.ToHexString(' ') : Encoding.ASCII.GetString(array2)));
							}
							base.RaiseDataReceived(array);
						}
						else
						{
							base.RemoveClient(appSession, "");
						}
					}
				}
				catch (ObjectDisposedException)
				{
				}
				catch (Exception ex)
				{
					ILogNet logNet3 = base.LogNet;
					if (logNet3 != null)
					{
						logNet3.WriteException(this.ToString(), StringResources.Language.SocketEndReceiveException, ex);
					}
					this.RefreshReceive();
				}
				finally
				{
				}
			}
		}

		/// <inheritdoc />
		// Token: 0x060009AC RID: 2476 RVA: 0x00039744 File Offset: 0x00037944
		public override string ToString()
		{
			return string.Format("MelsecMcUdpServer[{0}]", base.Port);
		}
	}
}
